<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
      width="65%"
      :disabled="readonlyFlag"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="抬头类型" prop="titleType">
            <el-select v-model="formData.titleType" placeholder="请选择抬头类型" class="w-1/1">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.CRM_RECEIPT_TITLE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="发票抬头" prop="title">
            <el-input v-model="formData.title" placeholder="请输入发票抬头" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="纳税人识别号" prop="taxCode">
            <el-input v-model="formData.taxCode" placeholder="请输入纳税人识别号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开户行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="请输入开户行" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="开户行账号" prop="bankAccount">
            <el-input v-model="formData.bankAccount" placeholder="请输入开户行账号" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="开票地址" prop="receiptAddress">
            <el-input v-model="formData.receiptAddress" placeholder="请输入开票地址" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="电话号码" prop="phoneNumber">
            <el-input v-model="formData.phoneNumber" placeholder="请输入电话号码" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="负责人" prop="ownerUserId">
            <el-select
              v-model="formData.ownerUserId"
              :disabled="formType !== 'create'"
              class="w-1/1"
            >
              <el-option
                v-for="item in userOptions"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="客户名称" prop="customerId">
            <el-select
              v-model="formData.customerId"
              class="w-1/1"
              filterable
              placeholder="请选择客户"
              @change="handleCustomerChange"
              :disabled="true"
            >
              <el-option
                v-for="item in customerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading" v-show="!readonlyFlag"
        >确 定</el-button
      >
      <el-button @click="((dialogVisible = false), (readonlyFlag = true))">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { ReceiptTitleApi, ReceiptTitle } from '@/api/crm/receipttitle'
import * as UserApi from '@/api/system/user'
import { useUserStore } from '@/store/modules/user'
import * as CustomerApi from '@/api/crm/customer'

/** crm发票抬头 表单 */
defineOptions({ name: 'ReceiptTitleForm' })

// 只读开关
const readonlyFlag = ref(true)

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  titleType: undefined,
  title: undefined,
  taxCode: undefined,
  bankName: undefined,
  bankAccount: undefined,
  receiptAddress: undefined,
  phoneNumber: undefined,
  ownerUserId: 0,
  customerId: 0
})
const formRules = reactive({})
const formRef = ref() // 表单 Ref

const userOptions = ref<UserApi.UserVO[]>([]) // 用户列表
const customerList = ref<CustomerApi.CustomerVO[]>([]) // 客户列表

/** 打开弹窗 */
const open = async (type: string, id?: number, customerId?: number) => {
  readonlyFlag.value = type == 'detail'
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()

  // 获得用户列表
  userOptions.value = await UserApi.getSimpleUserList()
  // 获取客户列表
  customerList.value = await CustomerApi.getCustomerSimpleList()
  // 默认新建时选中自己
  if (formType.value === 'create') {
    formData.value.ownerUserId = useUserStore().getUser.id
    formData.value.customerId = customerId
  }

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ReceiptTitleApi.getReceiptTitle(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ReceiptTitle
    if (formType.value === 'create') {
      await ReceiptTitleApi.createReceiptTitle(data)
      message.success(t('common.createSuccess'))
    } else {
      await ReceiptTitleApi.updateReceiptTitle(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    titleType: undefined,
    title: undefined,
    taxCode: undefined,
    bankName: undefined,
    bankAccount: undefined,
    receiptAddress: undefined,
    phoneNumber: undefined,
    ownerUserId: 0
  }
  formRef.value?.resetFields()
}
</script>
